package data.join.com.media;

import android.content.Context;
import android.text.TextUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import data.join.com.application.EventMessage;
import data.join.com.network.RetrofitManager;
import data.join.com.socket.RegisterInfo;
import data.join.com.utils.BaseThread;
import data.join.com.utils.MyLog;
import data.join.com.utils.QuickShPref;
import data.join.com.utils.WakeLockUtils;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/10/23.
 */

public class DeviceRegisterThread extends BaseThread {

    private String TAG = DeviceRegisterThread.class.getSimpleName();

    private static DeviceRegisterThread registerThread;

    private Context mContext;

    private boolean isDeviceRegister;

    private DeviceRegisterThread(Context context){
        this.mContext = context;
        isDeviceRegister = false;
    }

    public static synchronized DeviceRegisterThread getInstance(Context context){
        if(registerThread == null){
            registerThread = new DeviceRegisterThread(context);
        }
        return registerThread;
    }

    @Override
    public void run() {
        while (true){
            WakeLockUtils.getDefault(mContext).acquireWakeLock(TAG);
            isDeviceRegister = deviceRegister();
            WakeLockUtils.getDefault(mContext).releaseWakeLock(TAG);

            if(isDeviceRegister){
                EventBus.getDefault().post(new EventMessage(EventMessage.DEVICES_REGISTER_SUCCESS));
                break;
            }else {
                await(TIME_WAIT);
            }
        }
    }

    private boolean deviceRegister(){
        boolean ret = false;

        String imei = QuickShPref.getInstance().getString(QuickShPref.DeviceImei);

        if(TextUtils.isEmpty(imei)){

            MyLog.E(TAG,"deviceRegister 设备IEMI为空");

        }else {
            Call<RegisterInfo> registerInfoCall = RetrofitManager.getApiService().devicesRegister(imei, AppUpdateThread.getVersionName(mContext));
            try {
                Response<RegisterInfo> response = registerInfoCall.execute();

                if(response.isSuccessful()){
                    RegisterInfo registerInfo = response.body();

                    if(registerInfo != null) {
                        QuickShPref.getInstance().putGsonClass(imei, registerInfo);
                        ret = true;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        MyLog.D(TAG,"deviceRegister ret="+ret);
        return ret;
    }

    public boolean isDevicesRegister(){
        return  isDeviceRegister;
    }
}
